import Request from '@/utils/luch-request/luch-request/index.js';
const http = new Request();
// 通常可以吧 baseUrl 单独放在一个 js 文件了
// const baseUrl = 'https://qthf.cdguguai.net.cn/api/'
const baseUrl = 'https://miantou.guguan.net/api/'
// const baseUrl = 'https://pastoral.guguan.net/web/'
const loginRequest = (options = {}) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + options.url || '',
			method: options.type || 'GET',
			data: options.data || {},
		}).then(data => {
			let [err, res] = data;
			resolve(res);
		}).catch(error => {
			reject(error)
		})
	});
}
const request = (options = {}) => {
	// 在这里可以对请求头进行一些设置
	let token='';
	if(uni.getStorageSync('TOKEN')){
		token=JSON.parse(uni.getStorageSync('TOKEN')).value;
	}
	options.header = {
		version: '2.7.0',
		token: token
	};
	return new Promise((resolve, reject) => {
		// uni.showLoading({
		// 	title: '加载中'
		// });
		uni.request({
			url: baseUrl + options.url || '',
			method: options.type || 'GET',
			data: options.data || {},
			header: options.header || {}
		}).then(data => {
			let [err, res] = data;
			// console.log("登录" + res.data.code);
			// if (res.data != null && res.data.code == 1000) {
			// console.error("请求成功，用户token失效，跳转登录页面")
			// uni.navigateTo({ //保留当前页并且跳转
			// 	url: '/packageB/login/login'
			// });
			// return;
			// }
			// uni.hideLoading();
			resolve(res);
		}).catch(error => {
			reject(error)
		})
	});
}
const login = (url, data, options = {}) => {
	options.type = 'GET';
	options.data = data;
	options.url = url;
	return loginRequest(options)
}

const get = (url, data, options = {}) => {
	options.type = 'GET';
	options.data = data;
	options.url = url;
	return request(options)
}

const post = (url, data, options = {}) => {
	options.type = 'POST';
	options.data = data;
	options.url = url;
	return request(options)
}
/**
 * 获取请求返回的res 从中获取sessionid 保存在缓存中
 */
const setSessionCookie = (res) => {
	var cookieStr = "";
	var cookieArr = new Array();
	res.cookies.forEach((item, index, array) => {
		cookieArr.push(item.split(";")[0]);
	});
	cookieStr = cookieArr.join(";");
	wx.setStorageSync('sessionid', cookieStr);
	console.debug("var cookie = " + cookieStr)
	http.setConfig((config) => {
		/* config 为默认全局配置*/
		config.baseURL = baseUrl; /* 根域名 */
		config.header = {
			AuthTokens: uni.getStorageSync('AuthTokens'), // 演示用
			cookie: uni.getStorageSync("sessionid") // 演示用
		}
		return config
	})
}

export default {
	request,
	get,
	post,
	login,
	setSessionCookie
}